package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket datagramSocket=null;
    public UdpEchoServer(int port){
        try {
            datagramSocket=new DatagramSocket(port);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    public void start(){
        System.out.println("服务器启动");
        while(true){
            DatagramPacket reuquestPacket=new DatagramPacket(new byte[4096],4096);
            try {
                datagramSocket.receive(reuquestPacket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //上述收到的是二进制数据,后续要进行打印操作,需要转成字符串
            String request=new String(reuquestPacket.getData(),0,reuquestPacket.getLength());
            //根据请求计算相应
            String response=process(request);
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,reuquestPacket.getSocketAddress());
            try {
                datagramSocket.send(responsePacket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.printf("[%s:%d] rep=%s resp=%s\n",reuquestPacket.getAddress(),reuquestPacket.getPort(),request,response);

        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) {
        UdpEchoServer udpEchoServer=new UdpEchoServer(9090);
        udpEchoServer.start();
    }


}
